/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { Drawer, Form, Row, Col, Input, Button, Radio, InputNumber, Tag, message } from 'antd';
import './style.scss';
import { useForm } from 'antd/lib/form/Form';
import { Store } from 'antd/lib/form/interface';
import { AutoWordModel, ModifyWordModelRequest } from 'admin/schema/WordModel';
import { autoWordModel, addWordModel, modifyWordModel } from 'admin/servers/servers';
import { RadioChangeEvent } from 'antd/lib/radio/interface';
import { useLocation } from 'react-router-dom';
import { clearNull } from 'utils/tools';
import qs from 'query-string';

type Props = {
  /**
   * 显示/隐藏抽屉弹框
   */
  show: boolean;
  /**
   * 意图Id(问答Id)
   */
  intentionId: number;
  /**
   * 当前编辑词模的数据
   */
  data?: ModifyWordModelRequest;
  /**
   * 关闭抽屉弹框事件
   */
  onClose: () => void;
  /**
   * 创建成功
   */
  onSuccess: () => void;
};

/**
 * 创建词模组件
 * 示例：AI管理-机器人管理-版本管理-配置话术流程-问答库-编辑-新建词模
 */
const AddWordModel: React.FC<Props> = props => {
  const [form] = useForm();
  // 弹窗类型：0-新建，1-编辑
  const [drawerMode, setDrawerMode] = useState<0 | 1>(0);
  // 自动生成词模-词模和词类
  const [autoWordModels, setAutoWordModels] = useState<AutoWordModel[]>([]);
  // 自动生成按钮loading
  const [autoButtonLoading, setAutoButtonLoading] = useState<boolean>(false);
  // 自动生成词模-词类
  const [wordClassList, setWordClassList] = useState<string[]>([]);
  // 确定按钮loading
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  // 路由location
  const location = useLocation();
  // URL查询字符串=>对象
  const query = useMemo(() => {
    return qs.parse(location.search);
  }, [location.search]);

  /**
   * 表单赋值&初始化
   */
  useEffect(() => {
    setDrawerMode(0);
    setAutoWordModels([]);
    setWordClassList([]);
    // props属性(词模)设置默认值
    if (props.data) {
      const {
        wordModelType = 0,
        wordModelOrder = 1,
        wordModelDescribe = '',
        wordModel = '',
        maxUnmatches = '',
      } = props.data;

      form.setFieldsValue({
        wordModelType,
        wordModelOrder,
        wordModelDescribe,
        wordModel,
        maxUnmatches,
      });
      setDrawerMode(1);
    }
  }, [form, props]);

  /**
   * 提取所有wordClassList数组
   */
  const getWordClassList = (autoWordModels: AutoWordModel[]): string[] => {
    let wordClassList: string[] = [];
    autoWordModels.forEach(item => {
      if (Array.isArray(item.wordClassList)) {
        wordClassList = wordClassList.concat(item.wordClassList);
      }
    });
    return Array.from(new Set(wordClassList));
  };

  /**
   * 自动生成词模
   */
  const handleAutoWordModels = useCallback(async () => {
    const { wordModelDescribe, wordModelType, wordModelOrder, maxUnmatches } =
      form.getFieldsValue();
    if (!wordModelDescribe.trim()) {
      message.info('请先输入例句');
      return;
    }
    setAutoButtonLoading(true);
    try {
      const res = await autoWordModel({
        wordModelDescribe: wordModelDescribe.trim(),
        intentionId: Number(props.intentionId),
        wordModelType: Number(wordModelType) === 0 ? 0 : 1,
        wordModelOrder: Number(wordModelOrder) === 0 ? 0 : 1,
        maxUnmatches: Number(maxUnmatches),
      });
      if (res.code === 0) {
        const data = res.data || [];
        setAutoWordModels(data);
        // 提取所有未识别的词类合并为一个数组
        setWordClassList(getWordClassList(data));
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setAutoButtonLoading(false);
  }, [form, props.intentionId]);

  /**
   * 选择系统推荐词模, 自动填充词模
   */
  const radioChange = (e: RadioChangeEvent) => {
    const { value } = e.target;
    form.setFieldsValue({
      wordModel: value,
    });
  };

  /**
   * 确认
   */
  const onFinish = useCallback(
    async (values: Store) => {
      console.log('onFinish -> values', values);
      setConfirmLoading(true);
      const { wordModel, wordModelType, wordModelDescribe, wordModelOrder, maxUnmatches } = values;
      try {
        let res: any;
        if (drawerMode) {
          res = await modifyWordModel(
            clearNull({
              wordModelId: props.data?.wordModelId,
              wordModel,
              wordModelType,
              wordModelDescribe,
              wordModelOrder,
              maxUnmatches,
            })
          );
        } else {
          res = await addWordModel(
            clearNull({
              intentionId: Number(props.intentionId),
              wordModel,
              wordModelType,
              wordModelDescribe,
              wordModelOrder,
              maxUnmatches,
            })
          );
        }
        if (res.code === 0) {
          // 成功
          const str = drawerMode ? '编辑成功' : '创建成功';
          message.success(str);
          props.onSuccess();
          form.resetFields();
        } else {
          // 失败
          message.error(`${res.tips}(错误码: ${res.code})`);
        }
      } catch (error) {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      }
      setConfirmLoading(false);
    },
    [drawerMode, form, props]
  );

  /**关闭弹窗 */
  const closeDrawer = () => {
    form.resetFields();
    props.onClose();
  };

  return (
    <>
      <Drawer
        title={drawerMode ? '编辑词模' : '新增词模'}
        placement="right"
        getContainer={false}
        width={720}
        closable={false}
        onClose={closeDrawer}
        visible={props.show}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={closeDrawer} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={() => form.submit()} type="primary" loading={confirmLoading}>
              确定
            </Button>
          </div>
        }
      >
        <Form
          layout="horizontal"
          labelCol={{ span: 4, offset: 0 }}
          form={form}
          initialValues={{
            wordModelType: 0,
            wordModelOrder: 1,
            wordModelDescribe: '',
            wordModel: '',
            maxUnmatches: '',
          }}
          onFinish={onFinish}
        >
          {/* <Form.Item name="wordModelType" label="词模类型">
            <Radio.Group>
              <Radio value={0}>普通词模</Radio>
              <Radio value={1}>排除词模</Radio>
            </Radio.Group>
          </Form.Item> */}
          <Form.Item
            label="词模问题"
            name="wordModelDescribe"
            rules={[{ required: true, whitespace: true }]}
            getValueFromEvent={event => {
              return event.target.value.replace(/\s+/g, '');
            }}
          >
            <Input placeholder="请输入词模问题" />
          </Form.Item>
          {/* <Form.Item label="词模问题">
            <Row gutter={8}>
              <Col span={16}>
                <Form.Item
                  name="wordModelDescribe"
                  rules={[{ required: true, whitespace: true }]}
                  getValueFromEvent={event => {
                    return event.target.value.replace(/\s+/g, "");
                  }}
                >
                  <Input placeholder="请输入词模问题" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Button
                  type="primary"
                  loading={autoButtonLoading}
                  onClick={() => handleAutoWordModels()}
                >
                  自动生成词模
                </Button>
              </Col>
            </Row>

            {autoWordModels.length > 0 && (
              <Form.Item>
                <div>系统推荐出以下词模</div>
                <Radio.Group onChange={radioChange}>
                  {autoWordModels.map(item => {
                    return (
                      <Radio
                        className="block-radio"
                        value={item.wordModel}
                        key={item.wordModel}
                      >
                        {item.wordModel}
                      </Radio>
                    );
                  })}
                </Radio.Group>
              </Form.Item>
            )}
            {wordClassList.length > 0 && (
              <Form.Item>
                <Row gutter={4}>
                  <Col span={20}>
                    以下词类不在【基础词库】中，如需添加请到【基础词库】模块添加
                  </Col>
                  <Col span={4}>
                    <Button
                      type="primary"
                      href={`/webapp/outbound/ai/robots/version/flow?versionId=${query.versionId}&type=basicWordLibrary`}
                      target="blank"
                    >
                      添加词模
                    </Button>
                  </Col>
                </Row>
                <Row>
                  {wordClassList.map((item, index) => {
                    return <Tag key={item + index}>{item}</Tag>;
                  })}
                </Row>
              </Form.Item>
            )}
          </Form.Item>
           */}
          {/* <Form.Item
            label="词模"
            name="wordModel"
            rules={[
              { required: true, whitespace: true },
              {
                message: "词模格式必须以”^”开始，以“$”结束",
                pattern: /^\^.*?\$$/,
              },
            ]}
            getValueFromEvent={event => {
              return event.target.value.replace(/\s+/g, "");
            }}
          >
            <Input.TextArea placeholder="请输入词模" />
          </Form.Item> */}
          {/* <Form.Item wrapperCol={{ offset: 4 }}>
            <a href="https://shimo.im/docs/PPkhGJyTY3kcVR8r" target="blank">
              词模填写规范请查看链接
            </a>
          </Form.Item> */}
          {/* <Form.Item label="词模设置">
            <Form.Item></Form.Item>
            <Form.Item name="wordModelOrder" label="顺序">
              <Radio.Group>
                <Radio value={1}>无序</Radio>
                <Radio value={0}>有序</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item name="maxUnmatches" label="最大未匹配字数">
              <InputNumber
                min={0}
                max={20}
                precision={0}
                placeholder="请输入0-20以内数字"
                style={{ width: 200 }}
              />
            </Form.Item>
          </Form.Item> */}
        </Form>
      </Drawer>
    </>
  );
};

export default AddWordModel;
